"""
配置管理模块
使用 Pydantic Settings 管理环境变量
"""
from typing import List, Optional
from pydantic_settings import BaseSettings
from pydantic import Field


class Settings(BaseSettings):
    """应用配置"""
    
    # ==================== 应用配置 ====================
    APP_NAME: str = "思和智库"
    APP_VERSION: str = "2.1.1"
    DEBUG: bool = True
    ENVIRONMENT: str = "production"  # development | production
    
    # ==================== 服务器配置 ====================
    HOST: str = "0.0.0.0"
    PORT: int = 3301
    RELOAD: bool = False
    
    # ==================== 数据库配置 ====================
    DATABASE_TYPE: str = "postgresql"
    DATABASE_HOST: str = "localhost"
    DATABASE_PORT: int = 5432
    DATABASE_NAME: str = "shihe_knowledgehub"
    DATABASE_USER: str = "postgres"
    DATABASE_PASSWORD: str = ""  # 从环境变量读取，不要硬编码
    DATABASE_POOL_SIZE: int = 20
    DATABASE_MAX_OVERFLOW: int = 10
    
    @property
    def DATABASE_URL(self) -> str:
        """数据库连接URL"""
        return f"{self.DATABASE_TYPE}://{self.DATABASE_USER}:{self.DATABASE_PASSWORD}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
    
    # ==================== 安全配置 ====================
    SECRET_KEY: str = "your-secret-key-here-change-in-production-min-32-chars"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 1440  # 24小时
    BCRYPT_ROUNDS: int = 12
    
    # ==================== Ollama 配置 ====================
    OLLAMA_BASE_URL: str = "http://localhost:11434"
    
    # LLM 模型
    OLLAMA_LLM_MODEL: str = "qwen2.5:7b"  # 开发环境用7b，生产环境用32b
    OLLAMA_TEMPERATURE: float = 0.7
    OLLAMA_TOP_P: float = 0.9
    OLLAMA_TOP_K: int = 40
    OLLAMA_MAX_TOKENS: int = 2048
    
    # Embedding 模型
    OLLAMA_EMBED_MODEL: str = "bge-m3"  # 中文优化模型，1024维
    OLLAMA_EMBED_DIMENSION: int = 1024  # bge-m3 的向量维度是 1024
    
    # ==================== PaddleOCR 配置 ====================
    OCR_ENGINE: str = "paddleocr"
    OCR_USE_GPU: bool = True
    OCR_LANG: str = "ch"  # 中英文混合
    OCR_USE_ANGLE_CLS: bool = True  # 启用方向检测
    OCR_DET_DB_THRESH: float = 0.3
    OCR_DET_DB_BOX_THRESH: float = 0.6
    
    # ==================== 文件存储配置 ====================
    DATA_DIR: str = "./data"
    
    @property
    def KNOWLEDGE_BASE_DIR(self) -> str:
        return f"{self.DATA_DIR}/knowledge_base"
    
    @property
    def PUBLIC_DOCS_DIR(self) -> str:
        return f"{self.KNOWLEDGE_BASE_DIR}/public"
    
    @property
    def USER_DOCS_DIR(self) -> str:
        return f"{self.KNOWLEDGE_BASE_DIR}/users"
    
    @property
    def SHARED_DOCS_DIR(self) -> str:
        return f"{self.KNOWLEDGE_BASE_DIR}/shared"
    
    @property
    def VECTOR_STORE_DIR(self) -> str:
        return f"{self.DATA_DIR}/vector_store"
    
    VECTOR_STORE_TYPE: str = "faiss"
    
    @property
    def LOG_DIR(self) -> str:
        return f"{self.DATA_DIR}/logs"
    
    LOG_LEVEL: str = "INFO"  # DEBUG | INFO | WARNING | ERROR
    LOG_ROTATION: str = "1 week"
    LOG_RETENTION: str = "30 days"
    
    @property
    def BACKUP_DIR(self) -> str:
        return f"{self.DATA_DIR}/backups"
    
    AUTO_BACKUP: bool = True
    BACKUP_INTERVAL: str = "daily"  # daily | weekly | monthly
    
    # ==================== 文件上传配置 ====================
    MAX_FILE_SIZE: int = 104857600  # 100MB
    ALLOWED_FILE_TYPES: List[str] = [
        "pdf", "docx", "xlsx", "pptx", 
        "doc", "xls", "ppt", 
        "md", "txt",
        "jpg", "jpeg", "png", "bmp"
    ]
    
    @property
    def UPLOAD_DIR(self) -> str:
        """上传文件存储目录"""
        return f"{self.DATA_DIR}/uploads"
    
    UPLOAD_TEMP_DIR: str = "/tmp/uploads"
    
    # ==================== RAG 配置 ====================
    # 文本分块
    CHUNK_SIZE: int = 500
    CHUNK_OVERLAP: int = 50
    CHUNK_METHOD: str = "recursive"  # recursive | character | token
    
    # 检索配置
    SEARCH_TOP_K: int = 10
    SEARCH_TYPE: str = "hybrid"  # vector | keyword | hybrid
    SIMILARITY_THRESHOLD: float = 0.7
    
    # 问答配置
    QA_MAX_CONTEXT_DOCS: int = 5
    QA_STREAM_OUTPUT: bool = True
    
    # ==================== 分类配置 ====================
    CLASSIFIER_MODE: str = "auto"  # auto | suggest | manual
    CLASSIFIER_CONFIDENCE_THRESHOLD: float = 0.75
    CLASSIFIER_USE_LLM: bool = True
    CATEGORY_CONFIG_FILE: str = "./config/category_config.yaml"
    
    # ==================== CORS 配置 ====================
    CORS_ORIGINS: List[str] = [
        "http://localhost:3300",
        "http://127.0.0.1:3300"
    ]
    CORS_ALLOW_CREDENTIALS: bool = True
    CORS_ALLOW_METHODS: List[str] = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
    CORS_ALLOW_HEADERS: List[str] = ["*"]
    
    # ==================== 性能配置 ====================
    WORKERS: int = 4
    
    # 缓存配置
    USE_REDIS_CACHE: bool = False
    REDIS_HOST: str = "localhost"
    REDIS_PORT: int = 6379
    REDIS_DB: int = 1
    CACHE_TTL: int = 3600  # 缓存过期时间（秒）
    
    # ==================== 其他配置 ====================
    TIMEZONE: str = "Asia/Shanghai"
    LANGUAGE: str = "zh_CN"
    DEMO_MODE: bool = False
    
    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = True
        extra = "allow"  # 允许额外字段（从.env文件读取的额外配置）


# 创建全局配置实例
settings = Settings()

